package com.vincent.controller.admin;

import com.vincent.common.R;
import com.vincent.common.ShiroComponent;
import com.vincent.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.codehaus.plexus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    private ShiroComponent shiroComponent;

    @PostMapping("/login")
    public R login(@RequestBody User user){
        if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return R.error("用户名或密码错误");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        subject.login(token);
        subject.getSession(true).setTimeout(shiroComponent.getSessionTimeout());
        return R.ok().put("user",SecurityUtils.getSubject().getPrincipal());
    }
}
